﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class CourseView : MonoBehaviour
{
	public int CourseID;
	public string url;
	ActionBase actionComponent;

	private void Start()
	{
		StartCoroutine(SpeechSynthesis("1111111111111", 5, 5, 5, 4));
		actionComponent = GameObject.Find("GameManager").GetComponent<ActionBase>();
		LoadCourse(CourseID);
	}





	public void LoadCourse(int courseId)
	{


		//var reqResult = Application.dataPath + "/Scripts/demo1.json";
		//PPTModel jsonModel = LoadJson<PPTModel>(reqResult);
		////ResolvePPT(jsonModel, false);
		if (Application.internetReachability == NetworkReachability.NotReachable)
		{
			if (Directory.Exists(Application.dataPath + "/Resources/Courses/" + courseId))
			{
				var path = Application.dataPath + "/Resources/Courses/" + courseId + "/demo1.Json";
				var pptmodel = LoadJson<PPTModel>(path);
				//TODO  1.传参
				ResolvePPT(pptmodel, true);
			}
			else
			{
				Debug.Log("没有数据");
			}
		}
		else
		{
			if (Directory.Exists(Application.dataPath + "/Resources/Courses/" + courseId))
			{
				var path = Application.dataPath + "/Resources/Courses/" + courseId + "/demo1.Json";
				var pptmodel = LoadJson<PPTModel>(path);

				ResolvePPT(pptmodel, true);
			}
			else
			{
				Debug.Log("开始创建文件夹");
				Directory.CreateDirectory(Application.dataPath + "/Resources/Courses/" + courseId);
				AssetDatabase.Refresh();
				StartCoroutine(DownLoadJson(url, "demo1.Json"));
			}

		}


	}

	//序列化JSON
	T LoadJson<T>(string path)
	{
		string fileText = File.ReadAllText(path, System.Text.Encoding.UTF8);
		T tModel = JsonConvert.DeserializeObject<T>(fileText);
		return tModel;
	}
	//解析ppt
	void ResolvePPT(PPTModel pmodel, bool isLocal)
	{

		foreach (var slide in pmodel.SlideList)
		{
			foreach (var item in slide.ElementList)
			{
				foreach (var sub in item.SubListItem)
				{
					//文本类
					if (item.Type == ItemType.Text)
					{

						InitText(sub);


					}
					//图片类
					else if (item.Type == ItemType.Image)
					{
						//是否已经下载：isLocal为true是直接本地加载为false是远程加载
						if (isLocal)
						{
#if UNITY_EDITOR
							var imgpath = "Courses/" + CourseID + "/" + sub.ItemName;
#elif UNITY_IPHONE || UNITY_ANDROID
                           var imgpath=Application.persistentDataPath + "Assets/Courses/" + CourseID + "/" + item.ItemName                    
#endif
							StartCoroutine(DownLoad(imgpath, sub, isLocal));
						}
						else
						{
							StartCoroutine(DownLoad(sub.Content, sub, isLocal));
						}
					}
					//按钮类
					else if (item.Type == ItemType.Button)
					{

					}
				}
			}
		}

	}
	GameObject InitText(SubItem item)
	{
		GameObject gameObj = Resources.Load<GameObject>("Prefab/Text");
		FixedPosition(item, gameObj, Screen.width, Screen.height);
		var text = gameObj.GetComponent<Text>();
		AttributeControll(text, item.Attributes);
		text.text = item.Content;
		var textGo = Instantiate(gameObj, transform);
		textGo.name = item.ID;
		BindingEvent(textGo, item);
		return textGo;
	}


	private void AttributeControll(Text text, Attribute attributes)
	{




		var colors = attributes.ItemColor.Split(',');

		text.color = new Color(float.Parse(colors[0]), float.Parse(colors[1]), float.Parse(colors[2]));
		text.fontSize = attributes.FontSize;

		text.fontStyle = attributes.Style;

	}

	//初始化图片资源
	GameObject InitImage(Texture2D texture, SubItem item)
	{

		GameObject gameObj = Resources.Load<GameObject>("Prefab/Image");
		FixedPosition(item, gameObj, Screen.width, Screen.height);
		var image = gameObj.GetComponent<Image>();
		image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, texture.height));
		var imageGo = Instantiate(gameObj, transform);
		imageGo.name = item.ID;
		BindingEvent(imageGo, item);
		return imageGo;

	}

	void FixedPosition(SubItem item, GameObject gameObj, float width, float height)
	{
		Vector2 positon = new Vector2(item.StartPosition.x, item.StartPosition.y);
		Vector2 scale = new Vector2(item.StartScale.x, item.StartScale.y);

		var rectTransform = gameObj.GetComponent<RectTransform>();
		rectTransform.anchorMax = new Vector2(0, 1);
		rectTransform.anchorMin = new Vector2(0, 1);
		rectTransform.pivot = new Vector2(0, 1);
		var sceenWidth = Screen.width;
		var sceenHeight = Screen.height;

		rectTransform.anchoredPosition = new Vector2(width * positon.x / 100, -height * positon.y / 100);
		rectTransform.sizeDelta = new Vector2(width * scale.x / 100, height * scale.y / 100);
	}

	void BindingEvent(GameObject go, SubItem item)
	{

		if (!string.IsNullOrEmpty(item.OnLoad))
		{
			//TODO 4.单例可直接调用
			ActionBase.ActionInstantiate.ExecAction(item.OnLoad, new object[] { go, Vector2.zero });
			//go.AddComponent(Type.GetType(item.OnLoad));
		}


		if (item.OnClikck != null)
		{
			EventTriggerListener.Get(go).onClick = (g) =>
			{

				Debug.Log("点击事件");
				foreach (var at in item.OnClikck)
				{
					var target = GameObject.Find(at.ID);
					target.AddComponent(Type.GetType(at.Action));
				}
			};
		}


		if (item.OnDrag != null)
		{

			var body = go.AddComponent<Rigidbody2D>();
			body.gravityScale = 0;
			var box = go.AddComponent<BoxCollider2D>();
			box.size = go.transform.GetComponent<RectTransform>().sizeDelta;
			box.offset = new Vector2(box.size.x * 0.5f, -box.size.y * 0.5f);



			string classname = "";

			foreach (var at in item.OnDrag)
			{
				var objs = GameObject.FindGameObjectsWithTag(at.ClassName);
				classname = at.ClassName;
				foreach (var obj in objs)
				{
					var collider = obj.AddComponent<BoxCollider2D>();
					collider.isTrigger = true;
					collider.size = obj.transform.GetComponent<RectTransform>().sizeDelta;
					//collider.offset = new Vector2(box.size.x * 0.5f, -box.size.y * 0.5f);
				}
			}




			DragEventListener.Get(go).onDrag = (g) =>
			{
				g.transform.position = Input.mousePosition;
			};
			DragEventListener.Get(go).onCollision = (collosion) =>
			{

				Debug.Log("碰撞触发");
				if (collosion.transform.tag == classname)
				{
					go.transform.SetParent(collosion.transform);
					go.transform.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
				}

			};


		}
		if (item.OnEndDarg != null)
		{
			DragEventListener.Get(go).onEndDrag = (g) =>
			{
				Debug.Log("拖动结束事件");
				foreach (var at in item.OnDrag)
				{
					g.transform.position = Input.mousePosition;
				}
			};

		}

	}
	//下载Json文件

	IEnumerator DownLoadJson(string url, string resource)
	{
		var www = new WWW(url + resource);
		yield return www;
		var str = www.text;
		try
		{
			if (Application.platform == RuntimePlatform.Android)
			{
				File.WriteAllText(Application.persistentDataPath + "/" + CourseID, str);
			}
			else
			{
				File.WriteAllText(Application.dataPath + "/Resources/Courses" + "/" + CourseID + "/" + resource, str);
			}
			AssetDatabase.Refresh();
			PPTModel jsonModel = LoadJson<PPTModel>(Application.dataPath + "/Resources/Courses" + "/" + CourseID + "/" + resource);
			ResolvePPT(jsonModel, false);

		}
		catch (IOException e)
		{
			print(e);
		}
	}
	//TODO 2.参数不应该赋值  路径判断
	//下载图片
	IEnumerator DownLoad(string url, SubItem item, bool islocal)
	{

		if (islocal)
		{
			Debug.Log("本地加载" + url);
			var texture = Resources.Load<Texture2D>(url);
			InitImage(texture, item);

		}
		else
		{
			Debug.Log("远程操作");
			var www = new WWW(url);
			yield return www;
			var texture = www.texture;
			InitImage(texture, item);
			byte[] pngData = texture.EncodeToPNG();
			try
			{
				Debug.Log(item.ItemName);
#if UNITY_EDITOR
				var imgpath = Application.dataPath + "/Resources/Courses" + "/" + CourseID + "/" + item.ItemName + ".png";
#elif UNITY_IPHONE || UNITY_ANDROID
                var imgpath=Application.persistentDataPath + "Assets/Courses/" + CourseID + "/" + item.ItemName                    
#endif
				Debug.Log(imgpath);
				File.WriteAllBytes(imgpath, pngData);
				AssetDatabase.Refresh();
			}
			catch (IOException e)
			{
				print(e);
			}
		}
	}


	IEnumerator GetAudioClip()
	{

		//string path = Application.dataPath + "/Audio" + "/10638.mp3";

		using (var uwr = UnityWebRequest.GetAudioClip("http://fjdx.sc.chinaz.com/Files/DownLoad/sound1/201809/10638.wav", AudioType.WAV))
		{
			yield return uwr.Send();
			if (uwr.isError)
			{
				Debug.LogError(uwr.error);
				yield break;
			}
			AudioClip clip = DownloadHandlerAudioClip.GetContent(uwr);
			Debug.Log("加载语音");
			var audioS = GameObject.Find("GameManager").transform.GetComponent<AudioSource>();

			audioS.clip = clip;
			audioS.Play();
		}
	}


	IEnumerator SpeechSynthesis(string content, int spd, int pit, int vol, int per, int aue = 6)
	{
		string token = "";
		string tokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=q76L3UASLrHxehq6IaVIMtSo&client_secret=9318e3e8e82e1381bb2535a2a3494613";
		string synthesisUrl = "https://tsn.baidu.com/text2audio";
		using (var uwr = UnityWebRequest.Get(tokenUrl))
		{
			yield return uwr.Send();
			if (uwr.isError)
			{
				Debug.LogError(uwr.error);
				yield break;
			}

			NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces();
			var mac = nis[0].GetPhysicalAddress().ToString();
			token = JsonConvert.DeserializeObject<BaiDuToken>(uwr.downloadHandler.text).access_token;
			Debug.Log(token);
			WWWForm data = new WWWForm();
			data.AddField("tex", WWW.UnEscapeURL(WWW.UnEscapeURL(content)));
			data.AddField("tok", token);
			data.AddField("cuid", mac);
			data.AddField("ctp", 1);
			data.AddField("lan", "zh");
			data.AddField("spd", spd);
			data.AddField("pit", pit);
			data.AddField("vol", vol);
			data.AddField("per", per);
			data.AddField("aue", aue);


			//			var param = new Dictionary<string, string>();
			//			param.Add("tex", WWW.UnEscapeURL(WWW.UnEscapeURL(content)));
			//			param.Add("tok", token);
			//			param.Add("cuid", SystemInfo.deviceUniqueIdentifier);
			//			param.Add("ctp", "1");
			//			param.Add("lan", "zh");
			//			param.Add("spd", Mathf.Clamp(spd, 0, 9).ToString());
			//			param.Add("pit", Mathf.Clamp(pit, 0, 9).ToString());
			//			param.Add("vol", Mathf.Clamp(vol, 0, 15).ToString());
			//			param.Add("per", ((int)per).ToString());
			//#if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP
			//			param.Add("aue", "6"); // set to wav, default is mp3
			//#endif

			//			string url = synthesisUrl;
			//			int i = 0;
			//			foreach (var p in param)
			//			{
			//				url += i != 0 ? "&" : "?";
			//				url += p.Key + "=" + p.Value;
			//				i++;
			//			}

			//#if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP
			//			var www = UnityWebRequest.GetAudioClip(url, AudioType.WAV);
			//#else
			//			            var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG);
			//#endif

			//			yield return www.Send();

			//			if (string.IsNullOrEmpty(www.error))
			//			{
			//				var type = www.GetResponseHeader("Content-Type");
			//				if (type.Contains("audio"))
			//				{
			//					var audioS = GameObject.Find("GameManager").transform.GetComponent<AudioSource>();
			//					var audioClip = DownloadHandlerAudioClip.GetContent(www);
			//					SaveAudio.Save(audioClip, Application.dataPath + "/2.wav");
			//					audioS.clip = audioClip;

			//					audioS.Play();

			//				}

			//			}




			using (var www = UnityWebRequest.Post(synthesisUrl, data))
			{



				yield return www.Send();
				if (www.isError)
				{
					Debug.LogError(www.error);
					yield break;
				}

				if (www.GetResponseHeader("Content-Type").Contains("audio"))
				{
					var audioS = GameObject.Find("GameManager").transform.GetComponent<AudioSource>();
					var btyes = File.ReadAllBytes(Application.dataPath + "/Audio/10638.wav");
					Debug.Log(btyes.Length);


					WAV wav = new WAV(btyes);

					Debug.Log(wav.ToString());

					AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, wav.ChannelCount, wav.Frequency, false);

					float[] samples = new float[audioClip.samples * audioClip.channels];
					for (int i = 0; i < samples.Length; i++)
					{
						int s = i / 2;
						if (i % 2 == 0)
						{
							samples[i] = wav.LeftChannel[s];
						}
						else
						{
							samples[i] = wav.RightChannel[s];
						}


					}
					audioClip.SetData(samples, 0);
					audioS.clip = audioClip;

					audioS.Play();
				}

			}









		}
	}
}
public class BaiDuToken
{

	public string access_token { get; set; }
	public string session_key { get; set; }
	public string scope { get; set; }
	public string refresh_token { get; set; }

	public string session_secret { get; set; }

	public int expires_in { get; set; }


}

